package com.zhouyiquan.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhouyiquan.reggie.common.CustomException;
import com.zhouyiquan.reggie.dto.SetmealDto;
import com.zhouyiquan.reggie.entity.Setmeal;
import com.zhouyiquan.reggie.entity.SetmealDish;
import com.zhouyiquan.reggie.mapper.SetmealMapper;
import com.zhouyiquan.reggie.service.SetmealDishService;
import com.zhouyiquan.reggie.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: 周益全 (https://gitee.com/zfovikqdev928)
 * @BugFeedBackEmail: zfovikqdev928@126.com
 * @Date: Create in 2022-10
 * @Description:
 * @Version:
 */
@Service
@Slf4j
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {

    @Autowired
    private SetmealDishService setmealDishService; //套餐与菜品的关联关系

    /**
     * 新增套餐，同时需要保存套餐和菜品的关联关系
     * @param setmealDto
     */
    @Override
    @Transactional
    public void saveWithDish(SetmealDto setmealDto) {
        //1、保存套餐基本信息
        this.save(setmealDto);

        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes(); //获取套餐id
        setmealDishes = setmealDishes.stream().map((item) -> {
            item.setSetmealId(setmealDto.getId());
            return item;
        }).collect(Collectors.toList());
        //2、保存套餐与菜品的关联关系
        setmealDishService.saveBatch(setmealDishes);

    }

    /**
     * 删除套餐，同时删除套餐与菜品的关联关系
     * @param ids
     */
    @Override
    @Transactional
    public void removeWithDish(List<Long> ids) {
        //1、先查询套餐状态，停售不能删除抛出异常，然后再删除关联的数据

        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(Setmeal::getId,ids);
        queryWrapper.eq(Setmeal::getStatus,1);
        int count = this.count(queryWrapper);
        if (count > 0){
            throw  new CustomException("套餐正在售卖中，不能删除");
        }
        this.removeByIds(ids); //先删除套餐表的数据，也就是 setmeal 表

        //2、再删除关联数据
        LambdaQueryWrapper<SetmealDish> setmealDishQueryWrapper = new LambdaQueryWrapper<>();
        setmealDishQueryWrapper.in(SetmealDish::getSetmealId,ids);
        setmealDishService.remove(setmealDishQueryWrapper); //再删除setmeal_dish种的setmeal_id
    }
}
